from django.shortcuts import render, redirect
from django.http import HttpResponse, StreamingHttpResponse
from django.db import models
from django.db.models import Sum
from . import models
from django.views.decorators.http import require_http_methods


def greet():
    return "hello world"


# Create your views here.
def home(request):
    sum = models.BookInfo.bookmanager.all()
    sum1 = models.PersonInfo.objects.filter()

    if request.method == "GET":
        form = MessageBoardForm()
        response = HttpResponse("SUCCESS")
        response.set_cookie("username", "zhiliao")
        return response
        # return render(request, 'home.html', context={"form": form})
    else:
        form = MessageBoardForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get("title")
            content = form.cleaned_data.get("content")
            email = form.cleaned_data.get("email")
            print(title, content, email)
            response = HttpResponse("SUCCESS")
            response.set_cookie("username", "zhiliao")
            return response
    # return render(request, "home.html", context=context)


def userapp(request):
    user_name = request.POST.get('user')
    user_password = request.POST.get('password')
    user_sex = request.POST.get('sex')
    return HttpResponse(user_name+user_password+user_sex+"  登录成功！ ")


def cookie(request):
    res = HttpResponse()
    res.set_cookie('ck1', 'zhang3')
    return res


def session(request):
    s1 = request.session.get('s1', '')
    request.session['s1'] = 'ali4'
    return HttpResponse('session'+s1)

from django.views.generic import View
from .models import MessageBoardForm

class IndexView(View):

    def get(self, request):
        form = MessageBoardForm()
        return render(request, 'home.html', context={"form": form})

    def post(self, request):
        form = MessageBoardForm(request.POST)

        if form.is_valid():
            title = form.cleaned_data.get("title")
            content = form.cleaned_data.get("content")
            email = form.cleaned_data.get("email")
            print(title, content, email)
            return HttpResponse("ok")


from rest_framework.views import APIView
from rest_framework.authentication import authenticate
from rest_framework import exceptions

class MyAuth():
    def authenticate(self, request):
        token = request._request.GET.get("token")
        if not token:
            raise exceptions.AuthenticationFailed("用户认证失败")

    def authenticate_header(self, request):
        pass


class Myview(APIView):
    authentication_classes = [MyAuth]

    def get(self, request):
        return HttpResponse(ret={'code':202, 'msg':'sss'}, status=201)
